package com.itheima.springboottlias.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.springboottlias.common.utils.JwtUtils;
import com.itheima.springboottlias.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Component
@Slf4j
public class DemoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==拦截成功==");

// token存在请求头里面
        String token = request.getHeader("Token");


        if (!StringUtils.hasText(token)) {
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
 //响应
            response.getWriter().write(json);
            return false;
        }
//验证
        try {
            JwtUtils.parseJWT(token);
            return true;

        } catch (Exception e) {
            Result not_login = Result.error("NOT_LOGIN");
            String json = JSON.toJSONString(not_login);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);

        }
        return false;

    }
}
